<template>
  <div class="node node-control">
    <div class="node-bar"></div>
    <div class="node-content">
      <div class="node-main">
        <!-- 悬停工具栏（删除） -->
        <NodeToolbar
          :node-id="id"
          :show-execute="false"
          :show-mute="false"
          :show-delete="true"
        />
        <div class="node-title">{{ data.label || '控制节点' }}</div>
        <div class="node-desc">{{ data.description || '控制类节点' }}</div>
        <!-- 入参摘要（仅展示前10项），值支持变量占位符的显示映射 -->
        <div v-if="kvPairs.length" class="kv-list" style="margin-top: 6px">
          <div v-for="it in kvPairs" :key="it.k" class="kv-item">
            <span class="kv-val">{{ it.v }}</span>
            <span class="kv-sep">:</span>
            <span class="kv-key">{{ it.k }}</span>
          </div>
        </div>
        <!-- 控制配置概要显示（兜底：未初始化也按全部满足显示） -->
        <div class="control-summary">
          <template v-if="controlMode === 'all'"> 全部满足 </template>
          <template v-else-if="controlMode === 'partial'">
            部分满足：{{ displaySelectedNodes.join(" ") }}
          </template>
          <template v-else-if="controlMode === 'any'">
            任意满足：{{ displaySelectedNodes.join(" ") }}
          </template>
        </div>
        <div class="node-branches" v-if="data.branches && data.branches.length">
          <div
            v-for="branch in data.branches"
            :key="branch.name"
            class="node-branch"
          >
            <span class="branch-label">{{ branch.name }}</span>
            <span class="branch-cond">{{ branch.condition }}</span>
          </div>
        </div>
        <!-- 出参展示：按 value key 顺序 -->
        <div v-if="outputsPairs.length" class="kv-list" style="margin-top: 6px">
          <div v-for="it in outputsPairs" :key="it.key" class="kv-item">
            <span class="kv-val">{{ it.value }}</span>
            <span class="kv-sep">:</span>
            <span class="kv-key">{{ it.key }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 左侧连接点（控制节点允许多入） -->
    <Handle
      type="target"
      :position="Position.Left"
      id="target"
      class="node-handle node-handle-left"
    />
    <!-- 右侧目标连接点：用于支持根据卡片右半自动吸附到右侧目标点 -->
    <Handle
      type="target"
      :position="Position.Right"
      id="target-right"
      class="node-handle node-handle-right"
    />
    <!-- 右侧连接点：控制节点通常单一出口；若配置了分支则按分支数量生成句柄（与条件节点一致的样式能力） -->
    <template v-if="data.branches && data.branches.length > 0">
      <Handle
        v-for="(branch, idx) in data.branches || []"
        :key="`source-${branch.id ?? idx}`"
        type="source"
        :position="Position.Right"
        :id="`source-${branch.id ?? idx}`"
        class="node-handle node-handle-right"
        :style="styleForBranch(idx, (data.branches || []).length)"
      />
    </template>
    <template v-else>
      <Handle
        type="source"
        :position="Position.Right"
        id="source"
        class="node-handle node-handle-right"
        :style="{ top: '50%' }"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, defineProps } from "vue";
import { Handle, Position } from "@vue-flow/core";
 
import { useWorkflowVariables } from "@/components/workflow/useWorkflowVariables";
import NodeToolbar from './NodeToolbar.vue'

interface Branch {
  id?: string;
  name: string;
  condition: string;
}

interface Props {
  id?: string;
  data: {
    label?: string;
    description?: string;
    branches?: Branch[];
    control?: {
      mode: "all" | "partial" | "any";
      selectedNodeKeys?: string[];
      selectedNodeLabels?: string[];
    };
    outputs?: Array<{ key: string; name?: string }>;
  };
}

const props = defineProps<Props>();

// 变量映射：value(${nodeKey,key}) -> display(${节点名称,key})
const { processVariables, outputVariables, systemVariables } =
  useWorkflowVariables();
const varDisplayMap = computed<Record<string, string>>(() => {
  const map: Record<string, string> = {};
  const all = [
    ...(processVariables?.value || []),
    ...(outputVariables?.value || []),
    ...(systemVariables?.value || []),
  ];
  for (const it of all) {
    const val = String((it as any)?.value ?? "");
    if (!val) continue;
    const dis = String((it as any)?.display ?? val);
    map[val] = dis;
  }
  return map;
});

// 入参 name=value 摘要，最多展示前 10 项
const kvPairs = computed(() => {
  const fd: any = (props as any).data?.formData || {};
  const entries = Object.entries(fd)
    .filter(([k]) => k !== undefined && k !== null && String(k).trim() !== "")
    .map(([k, v]) => ({ k: String(k), v: formatVal(v) }));
  return entries.slice(0, 10);
});

function formatVal(v: any): string {
  if (v === null || v === undefined) return "";
  if (Array.isArray(v)) return v.map((x) => formatVal(x)).join(", ");
  if (typeof v === "object") return JSON.stringify(v);
  const s = String(v);
  const dis = varDisplayMap.value[s];
  return dis ?? s;
}

// 用于展示列表：优先 labels，否则 keys
const displaySelectedNodes = computed(() => {
  const c = props.data?.control as any;
  if (!c) return [] as string[];
  const labels = Array.isArray(c.selectedNodeLabels)
    ? c.selectedNodeLabels
    : [];
  const keys = Array.isArray(c.selectedNodeKeys) ? c.selectedNodeKeys : [];
  return (labels.length > 0 ? labels : keys).map((s: any) => String(s));
});

// 控制模式兜底：未初始化时默认显示为全部满足
const controlMode = computed<'all' | 'partial' | 'any'>(() => {
  const m = (props as any).data?.control?.mode;
  return m === 'partial' || m === 'any' ? m : 'all';
});

// 与 conditionNode 一致的分支句柄垂直分布计算
function styleForBranch(index: number, total: number) {
  if (total <= 1) {
    return { top: "50%" };
  }
  const min = 20;
  const max = 80;
  const step = (max - min) / (total - 1);
  const topPct = min + step * index;
  return { top: `${topPct}%` };
}

// 出参对（按 value key 顺序渲染），value 使用 name，key 使用 key
const outputsPairs = computed(() => {
  const list = Array.isArray((props as any).data?.outputs)
    ? ((props as any).data?.outputs as Array<any>)
    : [];
  return list
    .filter((it) => it && String(it.key || "").trim() !== "")
    .map((it) => ({ key: String(it.key), value: String(it.name || "") }));
});

// 删除事件由 NodeToolbar 内部处理
</script>

<style scoped>
.node {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px var(--node-shadow, rgba(0, 0, 0, 0.08));
  min-width: 240px;
  max-width: 360px;
  border: 1.5px solid #e5e7eb;
  overflow: visible;
  margin: 0;
  padding: 0;
  transition:
    box-shadow 0.2s,
    border 0.2s;
  cursor: pointer;
  position: relative;
}

/* 悬停时显示来自子组件的工具栏 */
.node:hover :deep(.node-toolbar) {
  display: flex;
}

.node-bar {
  width: 8px;
  background: #3b82f6; /* 蓝色条，区分控制节点 */
  border-top-left-radius: 14px;
  border-bottom-left-radius: 14px;
}

.node-content {
  display: flex;
  align-items: flex-start;
  padding: 14px 10px 14px 16px;
  flex: 1;
}

.node-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.node-title {
  font-weight: 600;
  color: #1d4ed8;
  font-size: 16px;
  margin-bottom: 2px;
}

.node-desc {
  color: #3b82f6;
  font-size: 13px;
  line-height: 1.3;
  margin-bottom: 8px;
}

.control-summary {
  color: #1d4ed8;
  font-size: 13px;
  background: #eff6ff;
  border-radius: 6px;
  padding: 4px 8px;
  margin-bottom: 8px;
}

.node-branches {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.node-branch {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  background: #eff6ff;
  border-radius: 6px;
  padding: 3px 8px;
  margin-bottom: 2px;
}

.branch-label {
  color: #1d4ed8;
  font-weight: 500;
}

.branch-cond {
  color: #64748b;
  font-size: 12px;
}

/* 连接点样式（与 conditionNode 一致，但使用蓝色） */
.node-handle {
  width: 12px !important;
  height: 12px !important;
  background: #3b82f6 !important;
  border: 2px solid #fff !important;
  border-radius: 50% !important;
  position: absolute !important;
  transform: translate(-50%, -50%) !important;
}

.node-handle-left {
  left: -6px !important;
  top: 50% !important;
}

.node-handle-right {
  right: -6px !important;
  top: 50% !important;
}

.node-handle:hover {
  background: #2563eb !important;
  transform: translate(-50%, -50%) scale(1.2) !important;
}

/* key-value 列表样式，与其他节点保持一致 */
.kv-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.kv-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #64748b;
}
.kv-key {
  color: #3b82f6;
}
.kv-val {
  color: #0f172a;
}
.kv-sep {
  opacity: 0.5;
}
</style>
